package com.zqwh.yj.sdk.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.util.Log;

import java.util.List;

/**
 * Created by eason.yang on 2017/9/21.
 */
public class SystemUtils {
    public static final int DEFAULT_TASK_NUM = 100;


    public static List<RunningTaskInfo> getRunningTask(Context context) {
        return getRunningTask(context, DEFAULT_TASK_NUM);
    }


    public static List<RunningTaskInfo> getRunningTask(Context context, int num) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> rTasks = am.getRunningTasks(1);
            return rTasks;
        }
        return null;
    }


    public static boolean isTopActivity(Activity activity) {
        return isTopActivity(activity, activity.getClass());
    }


    public static boolean isTopActivity(Context context,
                                        Class<? extends Activity> activity) {
        return isTopActivity(context, activity.getName());
    }


    /**
     * 判断当前的activity是否为top activity
     * @param context
     * @param className
     * @return
     */
    public static boolean isTopActivity(Context context, String className) {
        List<RunningTaskInfo> rTasks = getRunningTask(context, 1);
        for (RunningTaskInfo task : rTasks) {
            Log.d("SystemUtils", "isTopActivity:" + task.topActivity.getClassName()
                    + "|" + className);
            if (task.topActivity.getClassName().equals(className)) {
                return true;
            }
        }


        return false;
    }

    /**
     * 判断当前应用的是否为前台task
     * 
     * @param context
     * @return
     */
    public static boolean isAppForgroud(Context context) {
        if (context != null) {
            String packName = context.getPackageName();
            List<RunningTaskInfo> rTasks = getRunningTask(context, 1);
            RunningTaskInfo task = rTasks.get(0);
            return packName.equalsIgnoreCase(task.topActivity.getPackageName());
        }
        return false;
    }


    /**
     * 判断当前应用的是否为后台task
     * 
     * @param context
     * @return
     */
    public static boolean isAppBackground(Context context) {
        if (context != null) {
            String packName = context.getPackageName();
            List<RunningTaskInfo> rTasks = getRunningTask(context, 1);
            RunningTaskInfo task = rTasks.get(0);
            return !packName
                    .equalsIgnoreCase(task.topActivity.getPackageName());
        }
        return false;
    }
}

